package com.sunny;

/**
 * @Author zsunny
 * @Date 2018/9/23 16:56
 * @Mail zsunny@yeah.net
 */
public class Solution {

    public static void main(String[] args) {

        Solution solution = new Solution();
        String s = "dbccabcabc";
        String t = "bca";
        System.out.println(solution.kmp(s, t));

    }

    public int[] getNext(String str){
        int[] next = new int[str.length()];
        next[0] = 0;
        for(int i=1, k = 0;i<str.length();i++){
            while (k > 0 && str.charAt(i) != str.charAt(k)){
                k = next[k-1];
            }
            if(str.charAt(i) == str.charAt(k)){
                k++;
            }
            next[i] = k;
        }
        return next;
    }

    public int kmp(String s, String t){
        int[] next = getNext(t);
        int i = 0;
        int j = 0;
        for(;i<s.length() && j<t.length();i++){
            while (j>0 && s.charAt(i) != t.charAt(j)){
                j = next[j-1];
            }
            if(s.charAt(i) == t.charAt(j))
                j++;
        }
        if(j == t.length()){
            return i-t.length();
        }
        return -1;
    }

}
